package com.soul.soulservice.email.imp;

import cn.hutool.core.util.RandomUtil;
import com.soul.soulcommon.utils.RedisUtils;
import com.soul.soulservice.email.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author lj
 */
@Slf4j
@Service
public class EmailServiceImp implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    /**
     * 发件人邮箱
     */
    @Value("${spring.mail.username}")
    private String username ;

    @Autowired
    private RedisUtils utils;
    /**
     * 发送邮箱验证码
     * @param email
     * @return
     */
    @Override
    public String sendEmailCode(String email) {
        // 创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        String emailCode = RandomUtil.randomNumbers(6);
        log.info(email + "获取验证码：" + emailCode + " 成功");
        //存入redis20分钟
        try {
            utils.set(email, emailCode, 20, TimeUnit.MINUTES);
        }catch (RuntimeException e){
            log.error("redis异常结果" + e.getMessage());
        }
        // 设置邮件主题
        message.setSubject("【老人康复】你此次重置密码的验证码是:" + emailCode);
        // 设置邮件发送者，昵称+<邮箱地址>
        message.setFrom("发件人" + '<' + username + '>');
        // 设置邮件接收者，可以有多个接收者，多个接受者参数需要数组形式
        message.setTo(email);
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText("你此次重置密码的邮箱验证码是" + emailCode + "，请在20分钟内输入验证码进行下一步操作。如非本人操作，请忽略本次邮件！");
        try {
            // 发送邮件
            javaMailSender.send(message);
            return emailCode;
        } catch (Exception e) {
            log.error("邮箱验证码异常结果: " + e.getMessage());
            return "发送验证码失败";
        }
    }
}
